import { Platform } from "../platform/platform";


/** 获取页面关键词 */
const getTopKeywords = (n = 3) => {
    const content = document.body.innerText;
    const words = content.split(/\s+/); // 按空格分割单词
    const frequency = {};
    words.forEach(word => {
        const lowerWord = word.toLowerCase(); // 转换为小写
        if (lowerWord.length > 2) { // 忽略过短的单词
            frequency[lowerWord] = (frequency[lowerWord] || 0) + 1;
        }
    });
    const topKeywords = Object.entries(frequency)
        .sort((a, b) => b[1] - a[1]) // 按词频降序排序
        .slice(0, n) // 取前n个关键词
        .map(([word, _freq]) => word); // 提取单词
    return topKeywords;
}
/** 获取页面title
 * @description 基于页面内容生成标题，1.如果页面中有<h1>、<h2>等标题标签，优先使用这些标签的内容。2.如果没有合适的标题标签，可以从正文内容中提取关键句子或关键词。3.提取页面内容中出现频率最高的几个关键词，并组合成标题
 */
const getTitle = () => {
    /** 提取元素中的关键句子 */
    const extractTitleFromElement = () => {
        const elements = document.querySelectorAll('*[data-seo-title]');
        for (let element of elements) {
            if (element.textContent?.trim()) {
                return element.textContent.trim();
            }
        }
        return null;
    };
    const keySentence = extractTitleFromElement();
    /** 提取标题标签内容 */
    const extractTitleFromHeaders = () => {
        const elements = document.querySelectorAll('h1, h2, h3');
        for (let element of elements) {
            if (element.textContent?.trim()) {
                return element.textContent.trim();
            }
        }
        return null;
    };
    /** 优先从标题标签中提取 */
    const titleFromHeaders = extractTitleFromHeaders();
    /** 从关键词中生成标题 */
    const keywords = getTopKeywords(1).join(' | ');
    let result = keySentence || titleFromHeaders || keywords;
    result = result.slice(0, 50);
    return result;
}

/** 获取页面的description */
const getDescription = () => {
    /** 提取元素中的关键句子 */
    const extractFromElement = () => {
        const elements = document.querySelectorAll('*[data-seo-desc]');
        for (let element of elements) {
            if (element.textContent?.trim()) {
                return element.textContent.trim();
            }
        }
        return null;
    };
    const keySentence = extractFromElement();
    /** 提取标题标签内容 */
    const extractFromHeaders = () => {
        const elements = document.querySelectorAll('p');
        for (let element of elements) {
            if (element.textContent?.trim()) {
                return element.textContent.trim();
            }
        }
        return null;
    };
    /** 优先从标题标签中提取 */
    const descFromHeaders = extractFromHeaders();
    /** 从关键词中生成标题 */
    let content = document.body.innerText.replace(/[\r\n]+/g,'');
    let result = keySentence || descFromHeaders || content;
    result = result.slice(0, 150);
    return result;
}

/** seo工具 */
export class SeoUtils {
    static setSeo(params = {}, autofill = true) {
        const { title = '', description = '', keywords = [] } = params;
        if (title) {
            uni.setNavigationBarTitle({
				title: title.slice(0, 50),
			});
        }
        if (Platform.isH5 === false) {
            return;
        }
        /** 设置 <meta name="description"> 标签 */
        let metaDescription = document.querySelector('meta[name="description"]');
        if (metaDescription === null) {
            metaDescription = document.createElement('meta');
            metaDescription.setAttribute('name', 'description');
            document.head.appendChild(metaDescription);
        }
        if (description) {
            metaDescription.content = description.slice(0, 150);
        }
        /** 设置 <meta name="keywords"> 标签 */
        let metaKeywords = document.querySelector('meta[name="keywords"]');
        if (metaKeywords === null) {
            metaKeywords = document.createElement('meta');
            metaKeywords.setAttribute('name', 'keywords');
            document.head.appendChild(metaKeywords);
        }
        if (keywords.length > 0) {
            const keywordsContent = keywords.join(',');
            metaKeywords.content = keywordsContent;
        }

        /** 自动填充 */
        if (autofill === false) {
            return;
        }
        /** 自动填充 title */
        if (title === '') {
            document.title = getTitle();
        }
        /** 自动填充 description */
        if (description === '') {
            metaDescription.content = getDescription();
        }
        /** 自动填充 keywords */
        if (keywords.length === 0) {
            const keywordsContent = getTopKeywords(3).join(',');
            metaKeywords.content = keywordsContent;
        }
    }

    static clean() {
        if (Platform.isH5 === false) {
            return;
        }
        document.title = '';
        const metaDescription = document.querySelector('meta[name="description"]');
        if(metaDescription){
            metaDescription.content = '';
        }
        const metaKeywords = document.querySelector('meta[name="keywords"]');
        if(metaKeywords){
            metaKeywords.content = '';
        }
    }

    static remove() {
        if (Platform.isH5 === false) {
            return;
        }
        document.title = '';
        const metaDescription = document.querySelector('meta[name="description"]');
        if(metaDescription){
            metaDescription.remove();
        }
        const metaKeywords = document.querySelector('meta[name="keywords"]');
        if(metaKeywords){
            metaKeywords.remove();
        }
    }
}